import { ref } from 'vue'
import { chat, getToken } from '@/api/baidu.js'
import { TOKEN } from '@/constant/storage.js'

export function useChat() {
	const message = ref([])
	
	const  _getToken = async () => {
		const token = uni.getStorageSync(TOKEN)
		
	
		if (!token) {
			const tokenRes = await getToken()	
			
			uni.setStorageSync(TOKEN, tokenRes.access_token)
			
			return tokenRes.access_token
		} else {
			return token
		}
	}
	
	
	async function send(content, useHistory = true) {
		const token = await _getToken()
		
		if (!useHistory) {
			message.value= []
		}
		
		message.value.push({
			role: "user",
			content
		})
		
		return chat({
			token,
			messages: message.value
		}).then((res) => {
			message.value.push({
				role: 'assistant',
				content: res.result
			})
		})
	}
	
	
	return  {
		send,
		message
	}	
}